//
//  CYDrawCashViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/11.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYDrawCashViewController.h"
#import "CYDataSourceDelegate.h"
#import "CYTransferCell.h"
#import "CYBankView.h"
#import "CYDrawCashHeaderView.h"
#import "CYPickerController.h"
#import "CYSuccessTipsView.h"
@interface CYDrawCashViewController (){
    NSURLSessionTask *_bindCartTask;
}
@property (nonatomic, strong) UITableView *tableview;//tableview
@property (nonatomic, strong) CYButton *enterBtn;//确认按钮
@property (nonatomic, strong) CYDataSource *datasource;
@property (nonatomic, strong) CYDelegate *delegate;
@property (nonatomic, strong) CYView  *alphaView;/*弹出选择列表的时候，半透明背景*/
@property (nonatomic, strong) CYBankView *bankList;//银行选择列表
@property (nonatomic, strong) CYPickerController *dateList;//时间选择列表
@property (nonatomic, copy) NSString  *select_current_title;/*获取的选中状态的cell的内容,并赋值给当前需要填入信息的cell的title*/
@property (nonatomic, assign) CGFloat editing_cellMaxY;/*输入框当前在屏幕的纵向坐标，以此判断是否被键盘遮挡*/
@property (nonatomic, strong) NSMutableDictionary *bindCardDict;//绑定银行卡信息

@end

@implementation CYDrawCashViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO,
    self.tableview.hidden = self.enterBtn.hidden = NO;
    self.alphaView.hidden = YES;
    self.bankList.hidden = self.dateList.hidden = NO;
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    // Do any additional setup after loading the view.
}

- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]init];
        [self setupTableview];
        [self.view addSubview:_tableview];
        
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, 0, 0));
        }];
    }
    return _tableview;
}

-(CYButton *)enterBtn{
    if (!_enterBtn) {
        
        _enterBtn = [[CYButton alloc]initWithTitle:@"确认信息" titleColor:[UIColor whiteColor] backgroundColor:ColorHex(0xf4333c) cornerRadius:AL(5.0)];
        [_enterBtn addTarget:self action:@selector(actionForEnterBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_enterBtn];
        
        [_enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).with.offset( - AL(PT(65)));
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(AUTO(230), 44));
        }];
    }
    return _enterBtn;
}

- (CYBankView *)bankList{
    if (!_bankList) {
        WS(self)
        _bankList = [[CYBankView alloc]initWithData:nil block:^(NSString *bank_id, NSString *bank) {
            [weakSelf setupBank:bank_id bank:bank];
        }];
        [self.view addSubview:_bankList];
        
        CGFloat currentCellMaxY = CGRectGetMaxY([_tableview rectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]);  //获取cell的Y向最大值
        [_bankList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - currentCellMaxY));
        }];
    }
    return _bankList;
}

- (CYPickerController *)dateList{
    if (!_dateList) {
        WS(self)
        _dateList = [[CYPickerController alloc]initWithBlock:^(NSString *data, NSInteger type, NSString *cancelOrEnter) {
            if (type == 0) [weakSelf setupDate:(NSString *)data action:cancelOrEnter];//选择时间
            else if(type == 1) [weakSelf setupCity:(NSString *)data action:cancelOrEnter];//选择地区
            else
                [weakSelf performSelector:@selector(actionForSigleTap)];
            
        }];
        
        [self.view addSubview:_dateList];
        [_dateList mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(_dateList.bounds.size);
        }];
    }
    return _dateList;
}

- (CYView *)alphaView{
    if (!_alphaView) {
        _alphaView = [[CYView alloc]initWithColor:[UIColor clearColor]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForSigleTap)];
        [_alphaView addGestureRecognizer:tap];
        [self.view addSubview:_alphaView];
        
        
        [_alphaView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0, 0, 0));
        }];
    }
    return _alphaView;
}

- (NSMutableDictionary *)bindCardDict{
    if (!_bindCardDict)
        _bindCardDict = [NSMutableDictionary dictionary];
    return _bindCardDict;
}

- (void)setupTableview{
    WS(self)
    _delegate = [[CYDelegate alloc]initWithCellHeight:AL(PT(90)) views:[CYDrawCashHeaderView getHeader] block:^(NSIndexPath *index) {
        
    }];
    
    _datasource = [[CYDataSource alloc]initWithData:[self getTitle] identifier:@"CYTransferCell" block:^(id cell, id data) {
        [weakSelf bind:cell data:data];
    }];
    _tableview.delegate = _delegate;
    _tableview.dataSource = _datasource;
    [_tableview setSeparatorInset:UIEdgeInsetsZero];
    [_tableview setLayoutMargins:UIEdgeInsetsZero];
    
}

- (void)selectCell:(NSIndexPath *)index{
    
}

- (void)bind:(CYTransferCell *)cell data:(NSDictionary *)dict{
    WS(self)
    cell.title = dict[@"title"];
    cell.textField.placeholder = dict[@"placeholedr"];
    cell.style = dict[@"style"];
    cell.mylist = ^(NSString *title) {
        if ([title isEqualToString:@"开户银行"] || [title isEqualToString:@"开户银行归属地"] || [title isEqualToString:@"存款时间"])
            [weakSelf.tableview endEditing:YES];
        if ([title isEqualToString:@"开户银行"])
            [weakSelf showBankList];
        else if ([title isEqualToString:@"开户银行归属地"])
            [weakSelf showCityList];
        else if ([title isEqualToString:@"存款时间"])
            [weakSelf showDateList];
        else if ([title isEqualToString:@"提款密码"])
            _editing_cellMaxY = CGRectGetMaxY([_tableview rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]]);
        else if ([title isEqualToString:@"确认密码"])
            _editing_cellMaxY =CGRectGetMaxY([_tableview rectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]]);
        else
            [weakSelf viewIdentifier];
    };
    cell.myblock = ^(id data) {
        [weakSelf bindBankCardDictWithKey:dict[@"title"] value:data];//保存输入的文字信息，传给服务器
    };
    
}

//弹出银行列表
- (void)showBankList{
    _alphaView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _bankList.transform = CGAffineTransformMakeTranslation(0, -_bankList.bounds.size.height);
    }];
}

//弹出城市列表
- (void)showCityList{
    
    _alphaView.hidden = NO;
    _dateList.typeStr = @"area";
    [UIView animateWithDuration:0.3 animations:^{
        _dateList.transform = CGAffineTransformMakeTranslation(0, -_dateList.bounds.size.height);
    }];
    
}

//弹出时间列表
- (void)showDateList{
    _alphaView.hidden = NO;
    _dateList.typeStr = @"date";
    [UIView animateWithDuration:0.3 animations:^{
        _dateList.transform = CGAffineTransformMakeTranslation(0, -_dateList.bounds.size.height);
    }];
    
}

//弹出键盘时候，判断是否遮挡输入框，
- (void)keyboardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    CGFloat map = SCREEN_HEIGHT - _editing_cellMaxY - NAVIBAR_HEIGHT - STATUS_HEIGHT - height - 10;
    if (map < 0)
        [UIView animateWithDuration:0.3 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, map);
            
        }];
}

- (void)viewIdentifier{
    [UIView animateWithDuration:0.3 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

//选取银行
- (void)setupBank:(NSString *)bank_id bank:(NSString *)bank{
    _alphaView.hidden = YES;
    if (!bank_id && !bank)
        return;
    CYTransferCell *cell = [_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell.textField.text = bank;
    cell.myblock(bank);
    [self bindBankCardDictWithKey:@"bank_id" value:bank_id];
}

//选择地区
- (void)setupCity:(NSString *)city action:(NSString *)cancelOrEnter{
    if (cancelOrEnter)
        _alphaView.hidden = YES;
    CYTransferCell *cell = [_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    cell.textField.text = city;
    cell.myblock(city);
}

//选择时间
- (void)setupDate:(NSString *)date action:(NSString *)cancelOrEnter{
    if (cancelOrEnter)
        _alphaView.hidden = YES;
    CYTransferCell *cell = [_tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    cell.textField.text = date;
    
}

//半透明背景单击触摸手势响应方法
- (void)actionForSigleTap{
    _alphaView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        _dateList.transform = CGAffineTransformIdentity;
        _bankList.transform = CGAffineTransformIdentity;
    }];
    
}
//确认信息
- (void)actionForEnterBtn{
    
    [_tableview endEditing:YES];
    [_bindCardDict setValue:[CYCache readDataWithKey:@"username"] forKey:@"username"];
    [_bindCardDict setValue:[CYCache readDataWithKey:@"token"] forKey:@"token"];
    
    //请求绑定银行卡
self.spareTask = [CYHttps POST:API_bindCart parameters:_bindCardDict showHUD:YES progress:nil success:^(id data) {
        DeLog(@"data %@",data);
        if (data)
            [CYSuccessTipsView showTitle:@"银行卡绑定卡成功!" buttonTitle:@"去提现" block:^{
                [self actionForToDrawCash];
            }];
    } failure:nil];
    
    
}
//绑定银行卡成功，去提现
- (void)actionForToDrawCash{
    Class vc = NSClassFromString(@"CYEnterDrawCashVC");
    [self.navigationController pushViewController:[vc new] animated:YES];
    
}

- (void)bindBankCardDictWithKey:(NSString *)key value:(NSString *)value{
    if ([key isEqualToString:@"真实姓名"])
        [self.bindCardDict setValue:value forKey:@"name"];
    else if ([key isEqualToString:@"开户银行"])
        [self.bindCardDict setValue:value forKey:@"bank_name"];
    else if ([key isEqualToString:@"银行卡号"])
        [self.bindCardDict setValue:value forKey:@"account"];
    else if ([key isEqualToString:@"开户银行归属地"])
        [self.bindCardDict setValue:value forKey:@"countname"];
    else if ([key isEqualToString:@"提款密码"])
        [self.bindCardDict setValue:value forKey:@"coin_password"];
    else if ([key isEqualToString:@"确认密码"])
        [self.bindCardDict setValue:value forKey:@"new_password"];
    else
        [self.bindCardDict setValue:value forKey:key];
    
}
- (NSMutableArray *)getTitle{
    NSArray *array = @[@[@{@"title":@"真实姓名",@"placeholedr":@"输入您的真实姓名",@"style":@"input"},@{@"title":@"开户银行",@"placeholedr":@"选择银行",@"style":@"selection"},
                         @{@"title":@"银行卡号",@"placeholedr":@"请输入您的银行卡号",@"style":@"input"}, @{@"title":@"开户银行归属地",@"placeholedr":@"选择归属地",@"style":@"selection"},
                         @{@"title":@"存款时间",@"placeholedr":@"选择日期",@"style":@"selection"}],
                       @[@{@"title":@"提款密码",@"placeholedr":@"设置提款密码",@"style":@"input"},@{@"title":@"确认密码",@"placeholedr":@"确认提款密码",@"style":@"input"}]];
    return (NSMutableArray *)array;
}

- (void)https{
    
    NSDictionary *para = @{@"username":[CYUser shareUser].username,
                           @"token":[CYUser shareUser].token};
    
  self.task = [CYHttps POST:API_isBindCart parameters:para showHUD:NO progress:nil success:^(id data) {
        DeLog(@"data %@",data);
    } failure:nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self https];
    
}

- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    self.navigationItem.title = @"提现";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
